﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      Global Role Assignment
// Created By:     Parker Zhou (parkerz@wicresoft.com)
// Created Date:   2011-1-27
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.UI.WebControls;
using ASBCC.Database.EntityFramework;

namespace ASBCC.Business
{
    /// <summary>
    /// Role assignment模块数据库访问类
    /// </summary>
    public class RoleAssignmentHelper
    {
        /// <summary>
        /// 获取某个模块，某个用户的权限
        /// </summary>
        public IEnumerable GetModuleRoles(string employeeNo, string belongsTo)
        {
            if (string.IsNullOrEmpty(belongsTo))
                throw new ArgumentException("Parameter 'belongsTo' can not be null or empty");
            if (string.IsNullOrEmpty(employeeNo))
                throw new ArgumentException("Parameter 'employeeNo' can not be null or empty");

            var sys = belongsTo.Split(',');

            using (var dc = new CCEntities())
            {
                var employee = dc.Employees.First(p => p.EmployeeNo == employeeNo);
                employee.Roles.Load();

                var roles = from t in dc.Roles
                            where !t.Disabled && t.Description != "+pcat+" && t.Description != "+country+"
                            orderby t.BelongsTo, t.IsAdmin
                            select t;
                var source = from t in roles.ToArray()
                             where sys.Contains(t.BelongsTo)
                             select new
                             {
                                 t.RoleID,
                                 t.Name,
                                 t.Description,
                                 t.IsAdmin,
                                 t.BelongsTo,
                                 Checked = employee.Roles.Contains(t) ? "checked" : "",
                             };
                return source.ToArray();
            }

            //if (!string.IsNullOrEmpty(employeeNo))
            //{
            //    using (var db = new CCEntities())
            //    {
            //        // get theEmployee's roles
            //        var theEmployee = db.Employees.FirstOrDefault(e => (e.IsEnabled == true && e.EmployeeNo == employeeNo));
            //        if (theEmployee == null) throw new Exception(string.Format("The Employee with {0} was not found", employeeNo));
            //        theEmployee.Roles.Load();
            //        IEnumerable<Role> roleEmployeeHas = null;
            //        if (belongsTo != SystemModule.Admin.ToString())
            //            roleEmployeeHas = theEmployee.Roles.Where(r => (r.Disabled == false && r.BelongsTo == belongsTo));
            //        else
            //            roleEmployeeHas = theEmployee.Roles.Where(r => (r.Disabled == false && r.IsAdmin));
            //        // get all roles
            //        IEnumerable<Role> allRoles = null;
            //        if (belongsTo != SystemModule.Admin.ToString())
            //            allRoles = db.Roles.Where(r => r.Disabled == false && r.BelongsTo == belongsTo);
            //        else
            //            allRoles = db.Roles.Where(r => r.Disabled == false && r.IsAdmin);

            //        var result = from p in allRoles
            //                     select new
            //                     {
            //                         RoleID = p.RoleID,
            //                         RoleName = p.Name,
            //                         Check = (roleEmployeeHas != null && roleEmployeeHas.FirstOrDefault(rh => rh.RoleID == p.RoleID) != null)
            //                         ? "checked=\"checked\""
            //                         : ""
            //                     };
            //        return result.ToArray();
            //    }
            //}
            //else
            //{
            //    using (var db = new CCEntities())
            //    {
            //        IEnumerable<Role> allRoles = null;
            //        if (belongsTo != SystemModule.Admin.ToString())
            //            allRoles = db.Roles.Where(r => r.Disabled == false && r.BelongsTo == belongsTo);
            //        else
            //            allRoles = db.Roles.Where(r => r.Disabled == false && r.IsAdmin);

            //        var result = from p in allRoles
            //                     select new
            //                     {
            //                         RoleID = p.RoleID,
            //                         RoleName = p.Name,
            //                         Check = ""
            //                     };
            //        return result.ToArray();
            //    }
            //}
        }

        /// <summary>
        /// actually add record in UserInRole
        /// </summary>
        public bool SetUserRoles(string EmployeeNameKey, List<int> RoleIDs, string BelongsTo, bool isNo)
        {
            if (string.IsNullOrEmpty(EmployeeNameKey)) throw new Exception("EmployeeNameKey can not be null");
            if (RoleIDs == null) throw new Exception("RoleIDs can not be null");
            if (string.IsNullOrEmpty(BelongsTo)) throw new Exception("BelongsTo can not be null");

            if (BelongsTo == SystemModule.Admin.ToString())
            {
                using (var db = new CCEntities())
                {
                    string emNo = "";
                    if (!isNo)
                    {
                        if (db.Employees.Count(e =>
                            (e.NameEN == EmployeeNameKey && e.IsEnabled == true && e.IsActived == true)) != 1)
                            return false;
                        //throw new Exception(string.Format("The Employee with {0} was not found", EmployeeNameKey));
                        emNo = db.Employees.First(e =>
                            (e.NameEN == EmployeeNameKey && e.IsEnabled == true && e.IsActived == true)).EmployeeNo;
                    }
                    else
                    {
                        emNo = EmployeeNameKey;
                    }

                    var roles = db.sp_deleteRolesByEmployeeNo(emNo,/* ignore */ "Admin", 1);
                    foreach (var rid in RoleIDs)
                    {
                        db.sp_addRoleToEmployeeNo(rid, emNo);
                    }
                }
                return true;
            }
            else if (BelongsTo == SystemModule.CCD.ToString() || BelongsTo == SystemModule.CCO.ToString())
            {
                using (var db = new CCEntities())
                {
                    string emNo = "";
                    if (!isNo)
                    {
                        if (db.Employees.Count(e =>
                            (e.NameEN == EmployeeNameKey && e.IsEnabled == true && e.IsActived == true)) != 1)
                            return false;
                        //throw new Exception(string.Format("The Employee with {0} was not found", EmployeeNameKey));
                        emNo = db.Employees.First(e =>
                            (e.NameEN == EmployeeNameKey && e.IsEnabled == true && e.IsActived == true)).EmployeeNo;
                    }
                    else
                    {
                        emNo = EmployeeNameKey;
                    }

                    //filter non ccs role
                    string role2s = string.Empty;
                    string roles = string.Empty;
                    foreach (int r in RoleIDs)
                    {
                        var rr = db.Roles.FirstOrDefault(p => p.RoleID == r);
                        if (rr == null) continue;
                        if (rr.BelongsTo == BelongsTo)
                        {
                            role2s += r.ToString() + ",";
                            roles += (r - 10000).ToString() + ",";
                        }
                    }
                    role2s = role2s.TrimEnd(',');
                    roles = roles.TrimEnd(',');
                    if (role2s == string.Empty) role2s = "0";
                    if (roles == string.Empty) roles = "0";
                    //role scope : domestic or overseas
                    string role2scope = string.Empty;
                    string rolescope = string.Empty;
                    foreach (int r in db.Roles.Where(r => r.BelongsTo == BelongsTo).Select(p => p.RoleID))
                    {
                        role2scope += r.ToString() + ",";
                        rolescope += (r - 10000).ToString() + ",";
                    }
                    role2scope = role2scope.TrimEnd(',');
                    rolescope = rolescope.TrimEnd(',');
                    if (role2scope == string.Empty) role2scope = "0";
                    if (rolescope == string.Empty) rolescope = "0";
                    db.sp_RoleAssignForCCS(emNo, role2s, roles, role2scope, rolescope);
                }
                return true;
            }
            else
            {
                using (var db = new CCEntities())
                {
                    string emNo = "";
                    if (!isNo)
                    {
                        if (db.Employees.Count(e =>
                            (e.NameEN == EmployeeNameKey && e.IsEnabled == true && e.IsActived == true)) != 1)
                            return false;
                        //throw new Exception(string.Format("The Employee with {0} was not found", EmployeeNameKey));
                        emNo = db.Employees.First(e =>
                            (e.NameEN == EmployeeNameKey && e.IsEnabled == true && e.IsActived == true)).EmployeeNo;
                    }
                    else
                    {
                        emNo = EmployeeNameKey;
                    }
                    db.sp_deleteRolesByEmployeeNo(emNo, BelongsTo, 0);
                    foreach (var r in RoleIDs)
                    {
                        db.sp_addRoleToEmployeeNo(r, emNo);
                    }
                }
                return true;
            }
        }

        public void CreateProjectMembers(string NameEN)
        {
            if (!String.IsNullOrEmpty(NameEN))
            {
                using (var dc = new CCEntities())
                {
                    dc.SP_CreateProjectMembers(1, NameEN);
                }
            }
        }

        /// <summary>
        /// 根据当前NameEN获取EmployeeNo
        /// </summary>
        public static string getEmployeeNo(string nameEN)
        {
            using (var dc = new CCEntities())
            {
                var employee = dc.Employees.FirstOrDefault(p => p.NameEN == nameEN && p.IsActived == true && p.IsEnabled == true);
                if (employee == null)
                {
                    return null;
                }
                return employee.EmployeeNo;
            }
        }

        /// <summary>
        /// 由EmployeeNo获取CIL
        /// </summary>
        /// <param name="employeeNo"></param>
        /// <returns></returns>
        public static string GetCILByEmployeeNo(string employeeNo)
        {
            using (var dc = new CCEntities())
            {
                var employee = dc.Employees.FirstOrDefault(p => p.EmployeeNo == employeeNo);
                if (employee == null)
                {
                    return null;
                }
                return employee.NameEN;
            }
        }

        /// <summary>
        ///  获取json动态显示Province的string
        /// </summary>
        public static string GetProvinceSelectString()
        {
            using (var dc = new CCEntities())
            {
                var provinces = dc.Provinces.Where(p => p.Disabled == false).ToArray().Distinct();
                string returnvalue = "\\\"--请选择--\\\":\\\"0\\\",";
                foreach (var province in provinces)
                {
                    returnvalue += "\\\"" + province.Name + "\\\":\\\"" + province.ProvinceID.ToString() + "\\\",";
                }
                return returnvalue.Substring(0, returnvalue.Length - 1);
            }
        }

        /// <summary>
        ///  获取json动态显示Category的string
        /// </summary>
        public static string GetCategorySelectString()
        {
            using (var dc = new CCEntities())
            {
                var categories = dc.Categories.Where(p => p.Disabled == false).ToArray().Distinct();
                string returnvalue = "\\\"--请选择--\\\":\\\"0\\\",";
                foreach (var category in categories)
                {
                    returnvalue += "\\\"" + category.Name + "\\\":\\\"" + category.CateID.ToString() + "\\\",";
                }
                return returnvalue.Substring(0, returnvalue.Length - 1);
            }
        }

        /// <summary>
        ///  获取json动态显示Cluster的string
        /// </summary>
        public static string GetClusterSelectString()
        {
            using (var dc = new CCEntities())
            {
                var clusters = dc.Clusters.Where(p => p.Disabled == false).ToArray().Distinct();
                string returnvalue = "\\\"--请选择--\\\":\\\"0\\\",";
                foreach (var cluster in clusters)
                {
                    returnvalue += "\\\"" + cluster.Name + "\\\":\\\"" + cluster.ClusterID.ToString() + "\\\",";
                }
                return returnvalue.Substring(0, returnvalue.Length - 1);
            }
        }

        /// <summary>
        ///  获取json动态显示Country的string
        /// </summary>
        public static string GetCountrySelectString()
        {
            using (var dc = new CCEntities())
            {
                var countries = dc.Countries.Where(p => p.Disabled == false).OrderBy(p => p.Name).ToArray().Distinct();
                string returnvalue = "\\\"--请选择--\\\":\\\"0\\\",";
                foreach (var country in countries)
                {
                    returnvalue += "\\\"" + country.Name + "(" + country.Description + ")" + "\\\":\\\"" + country.CountryID.ToString() + "\\\",";
                }
                return returnvalue.Substring(0, returnvalue.Length - 1);
            }
        }

        /// <summary>
        ///  获取json动态显示Region的string
        /// </summary>
        public static string GetRegionSelectString()
        {
            using (var dc = new CCEntities())
            {
                var regions = dc.Areas.Where(p => p.Disabled == false).OrderBy(p => p.AreaID).ToArray().Distinct();
                string returnvalue = "\\\"--请选择--\\\":\\\"0\\\",";
                foreach (var region in regions)
                {
                    returnvalue += "\\\"" + region.Name + "(" + region.Description + ")" + "\\\":\\\"" + region.AreaID.ToString() + "\\\",";
                }
                return returnvalue.Substring(0, returnvalue.Length - 1);
            }
        }


        /// <summary>
        /// 更新CID用户权限
        /// </summary>
        public static bool UpdateUser(bool isAdmin, bool isReviewer, string commercialp, string commercialc, string cluster, string catvp, string dpso, string pso, string salesp, string salesc, string cil)
        {
            using (var dc = new CCEntities())
            {
                var user = dc.Employees.FirstOrDefault(p => p.NameEN == cil && p.IsActived == true);
                if (user == null)
                    return false;
                var roles = dc.Roles.Where(p => p.Description == "+pcat+" && p.Disabled == false).ToArray();
                var admin = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.IsAdmin == true);
                var read = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID Read");
                var write = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID Write");
                var reviewer = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID Reviewer");
                var commercial = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID Commercial");
                var clust = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID Cluster");
                var catv = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID CATVP");
                var PSO = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID PSO");
                var DPSO = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID DPSO");
                var sale = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID Sales");

                //去权限
                user.Roles.Load();
                foreach (var role in user.Roles.Where(p => p.BelongsTo == "CID" && p.Disabled == false).ToArray())
                    user.Roles.Remove(role);
                //Admin
                if (isAdmin)
                {
                    user.Roles.Add(admin);
                    dc.SaveChanges();
                    return true;
                }
                //Reviewer
                if (isReviewer)
                {
                    user.Roles.Add(reviewer);
                }
                //Commercial Province
                if (!String.IsNullOrEmpty(commercialp) && commercialp != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == write.RoleID).Count() < 1)
                        user.Roles.Add(write);
                    if (user.Roles.Where(p => p.RoleID == commercial.RoleID).Count() < 1)
                        user.Roles.Add(commercial);
                    var ps = commercialp.Split(',');
                    var cs = commercialc.Split(',');
                    for (int i = 0; i < ps.Length; i++)
                    {
                        if (!String.IsNullOrEmpty(ps[i]) && ps[i] != "0" && (String.IsNullOrEmpty(cs[i]) || cs[i] == "0"))
                        {
                            foreach (var role in roles)
                            {
                                if (role.Name.Contains(ps[i] + ";") && user.Roles.Where(p => p.RoleID == role.RoleID).Count() < 1)
                                {
                                    user.Roles.Add(role);
                                }
                            }
                        }
                    }
                }
                //Commercial Category
                if (!String.IsNullOrEmpty(commercialc) && commercialc != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == write.RoleID).Count() < 1)
                        user.Roles.Add(write);
                    if (user.Roles.Where(p => p.RoleID == commercial.RoleID).Count() < 1)
                        user.Roles.Add(commercial);
                    var rolep = dc.Provinces.FirstOrDefault(p => p.Name == "总部");
                    var cs = commercialc.Split(',');
                    foreach (var cc in cs)
                    {
                        if (rolep != null)
                        {
                            string rolename = rolep.ProvinceID.ToString() + ";" + cc;
                            var rolep2 = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.Name == rolename);
                            if (rolep2 != null && user.Roles.Where(p => p.RoleID == rolep2.RoleID).Count() < 1)
                                user.Roles.Add(rolep2);
                        }
                    }
                }
                //Cluster
                if (!String.IsNullOrEmpty(cluster) && cluster != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == read.RoleID).Count() < 1)
                        user.Roles.Add(read);
                    if (user.Roles.Where(p => p.RoleID == clust.RoleID).Count() < 1)
                        user.Roles.Add(clust);
                    var cls = cluster.Split(',');
                    foreach (var cl in cls)
                    {
                        if (!String.IsNullOrEmpty(cl))
                        {
                            int ci = int.Parse(cl);
                            var clus = dc.Clusters.FirstOrDefault(p => p.ClusterID == ci && p.Disabled == false);
                            if (clus != null)
                            {
                                clus.Provinces.Load();
                                foreach (var pro in clus.Provinces)
                                {
                                    foreach (var role in roles)
                                    {
                                        if (role.Name.Contains(pro.ProvinceID.ToString() + ";") && user.Roles.Where(p => p.RoleID == role.RoleID).Count() < 1)
                                            user.Roles.Add(role);
                                    }
                                }
                            }
                        }
                    }
                }
                //Catvp
                if (!String.IsNullOrEmpty(catvp) && catvp != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == read.RoleID).Count() < 1)
                        user.Roles.Add(read);
                    if (user.Roles.Where(p => p.RoleID == catv.RoleID).Count() < 1)
                        user.Roles.Add(catv);
                    var catvs = catvp.Split(',');
                    foreach (var ca in catvs)
                    {
                        if (!String.IsNullOrEmpty(ca) && ca != "0")
                        {
                            foreach (var role in roles)
                            {
                                if (role.Name.Contains(";" + ca) && user.Roles.Where(p => p.RoleID == role.RoleID).Count() < 1)
                                {
                                    user.Roles.Add(role);
                                }
                            }
                        }
                    }
                }
                //DPSO
                if (!String.IsNullOrEmpty(dpso) && dpso != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == read.RoleID).Count() < 1)
                        user.Roles.Add(read);
                    if (user.Roles.Where(p => p.RoleID == DPSO.RoleID).Count() < 1)
                        user.Roles.Add(DPSO);
                    var dps = dpso.Split(',');
                    foreach (var pp in dps)
                    {
                        if (!String.IsNullOrEmpty(pp) && pp != "0")
                        {
                            foreach (var role in roles)
                            {
                                if (role.Name.Contains(pp + ";") && user.Roles.Where(p => p.RoleID == role.RoleID).Count() < 1)
                                {
                                    user.Roles.Add(role);
                                }
                            }
                        }
                    }
                }
                //PSO
                if (!String.IsNullOrEmpty(pso) && pso != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == read.RoleID).Count() < 1)
                        user.Roles.Add(read);
                    if (user.Roles.Where(p => p.RoleID == PSO.RoleID).Count() < 1)
                        user.Roles.Add(PSO);
                    var dps = pso.Split(',');
                    foreach (var pp in dps)
                    {
                        if (!String.IsNullOrEmpty(pp) && pp != "0")
                        {
                            foreach (var role in roles)
                            {
                                if (role.Name.Contains(pp + ";") && user.Roles.Where(p => p.RoleID == role.RoleID).Count() < 1)
                                {
                                    user.Roles.Add(role);
                                }
                            }
                        }
                    }
                }
                //sales
                if (!String.IsNullOrEmpty(salesp) && !String.IsNullOrEmpty(salesc) && salesp != "0" && salesc != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == read.RoleID).Count() < 1)
                        user.Roles.Add(read);
                    if (user.Roles.Where(p => p.RoleID == sale.RoleID).Count() < 1)
                        user.Roles.Add(sale);
                    var ps = salesp.Split(',');
                    var cs = salesc.Split(',');
                    for (int i = 0; i < ps.Length; i++)
                    {
                        if (!String.IsNullOrEmpty(ps[i]) && !String.IsNullOrEmpty(cs[i]))
                        {
                            string pcat = ps[i] + ";" + cs[i];
                            var role = roles.FirstOrDefault(p => p.Name == pcat);
                            if (role != null)
                                user.Roles.Add(role);
                        }
                    }
                }

                dc.SaveChanges();
                return true;
            }
        }

        /// <summary>
        /// 获取CID用户权限
        /// </summary>
        /// <param name="cil"></param>
        /// <returns></returns>
        public static string GetUserRole(string cil)
        {
            using (var dc = new CCEntities())
            {
                var user = dc.Employees.FirstOrDefault(p => p.NameEN == cil);
                string result = "";
                List<Role> addedRoles = new List<Role>();//保存已查找的Role
                user.Roles.Load();
                var roles = user.Roles.Where(p => p.Disabled == false && p.Description == "+pcat+").ToArray();
                var provinces = dc.Provinces.Where(p => p.Disabled == false).ToArray();
                var categories = dc.Categories.Where(p => p.Disabled == false).ToArray();
                if (user.Roles.Where(p => p.Disabled == false && p.BelongsTo == "CID" && p.IsAdmin == true).Count() > 0)
                {
                    result = "Admin,";
                    return result;
                }
                if (user.Roles.Where(p => p.Disabled == false && p.BelongsTo == "CID" && p.Name == "CID Reviewer").Count() > 0)
                {
                    result = "Reviewer,";
                }
                if (user.Roles.Where(p => p.Disabled == false && p.Name == "CID Cluster").Count() > 0)
                {
                    var clusters = dc.Clusters.Where(p => p.Disabled == false).ToArray();
                    foreach (var cluster in clusters)
                    {
                        cluster.Provinces.Load();
                        bool flag = false;
                        foreach (var pro in cluster.Provinces)
                        {
                            flag = (from u in roles
                                    where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                                    select u).Count() == categories.Count();
                            if (flag == false)
                                break;
                        }
                        if (flag)
                        {
                            result += "Cluster;" + cluster.ClusterID.ToString() + ",";
                            foreach (var pro in cluster.Provinces)
                            {
                                addedRoles.AddRange((from u in roles
                                                     where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                                                     select u).ToList<Role>());
                            }
                        }
                    }
                }

                if (user.Roles.Where(p => p.Disabled == false && p.Name == "CID CATVP").Count() > 0)
                {
                    foreach (var pro in categories)
                    {
                        if ((from u in roles
                             where u.Name.Contains(";" + pro.CateID.ToString())
                             select u).Count() == provinces.Count())
                        {
                            result += "Catvp;" + pro.CateID.ToString() + ",";
                            addedRoles.AddRange((from u in roles
                                                 where u.Name.Contains(";" + pro.CateID.ToString())
                                                 select u).ToList<Role>());
                        }
                    }
                }

                if (user.Roles.Where(p => p.Disabled == false && p.Name == "CID Commercial").Count() > 0)
                {
                    foreach (var pro in provinces)
                    {
                        if ((from u in roles
                             where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                             select u).Count() == categories.Count() &&
                             (from u in addedRoles
                              where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                              select u).Count() == 0)
                        {
                            result += "CommercialP;" + pro.ProvinceID.ToString() + ",";
                            addedRoles.AddRange((from u in roles
                                                 where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                                                 select u).ToList<Role>());
                        }
                    }
                    var others = dc.Provinces.FirstOrDefault(p => p.Name == "总部");
                    string othersID = others != null ? others.ProvinceID.ToString() : null;
                    if (othersID != null)
                        foreach (var cat in categories)
                        {
                            if ((from u in roles
                                 where u.Name == othersID + ";" + cat.CateID.ToString()
                                 select u).Count() > 0 &&
                                (from u in addedRoles
                                 where u.Name == othersID + ";" + cat.CateID.ToString()
                                 select u).Count() < 1)
                            {
                                result += "CommercialC;" + cat.CateID.ToString() + ",";
                                addedRoles.AddRange((from u in roles
                                                     where u.Name.Contains(";" + cat.CateID.ToString())
                                                     select u).ToList<Role>());
                            }
                        }
                }

                if (user.Roles.Where(p => p.Disabled == false && p.Name == "CID DPSO").Count() > 0)
                {
                    foreach (var pro in provinces)
                    {
                        if ((from u in roles
                             where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                             select u).Count() == categories.Count() &&
                             (from u in addedRoles
                              where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                              select u).Count() == 0)
                        {
                            result += "DPSO;" + pro.ProvinceID.ToString() + ",";
                            addedRoles.AddRange((from u in roles
                                                 where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                                                 select u).ToList<Role>());
                        }
                    }
                }

                if (user.Roles.Where(p => p.Disabled == false && p.Name == "CID PSO").Count() > 0)
                {
                    foreach (var pro in provinces)
                    {
                        if ((from u in roles
                             where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                             select u).Count() == categories.Count() &&
                             (from u in addedRoles
                              where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                              select u).Count() == 0)
                        {
                            result += "PSO;" + pro.ProvinceID.ToString() + ",";
                            addedRoles.AddRange((from u in roles
                                                 where u.Name.Contains(pro.ProvinceID.ToString() + ";")
                                                 select u).ToList<Role>());
                        }
                    }
                }

                if (user.Roles.Where(p => p.Disabled == false && p.Name == "CID Sales").Count() > 0)
                {
                    var remainRoles = roles.ToList<Role>().Except(addedRoles).ToList<Role>();
                    foreach (var role in remainRoles)
                    {
                        result += "Sales;" + role.Name + ",";
                    }
                }
                return result;
            }
        }


        /// <summary>
        /// 更新CIO用户权限
        /// </summary>
        public static bool UpdateUserOver(bool isAdmin, string country, string region, string cil)
        {
            using (var dc = new CCEntities())
            {
                var user = dc.Employees.FirstOrDefault(p => p.NameEN == cil && p.IsActived == true);
                if (user == null)
                    return false;
                var roles = dc.Roles.Where(p => p.Disabled == false && p.Description == "+country+").ToArray();
                var admin = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.Name == "CIO Admin");
                var use = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.Name == "CIO User");
                user.Roles.Load();
                foreach (var role in user.Roles.Where(p => p.BelongsTo == "CIO" && p.Disabled == false).ToArray())
                    user.Roles.Remove(role);
                if (isAdmin)
                {
                    user.Roles.Add(admin);
                    dc.SaveChanges();
                    return true;
                }

                if (!String.IsNullOrEmpty(country) && country != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == use.RoleID).Count() < 1)
                        user.Roles.Add(use);
                    var countries = country.Split(',');
                    foreach (var coun in countries)
                    {
                        if (!String.IsNullOrEmpty(coun) && coun != "0")
                        {
                            foreach (var role in roles)
                            {
                                if (role.Name == coun && user.Roles.Where(p => p.RoleID == role.RoleID).Count() < 1)
                                {
                                    user.Roles.Add(role);
                                    break;
                                }
                            }
                        }
                    }

                }

                if (!String.IsNullOrEmpty(region) && region != "0")
                {
                    if (user.Roles.Where(p => p.RoleID == use.RoleID).Count() < 1)
                        user.Roles.Add(use);
                    var regions = region.Split(',');
                    foreach (var reg in regions)
                    {
                        if (!String.IsNullOrEmpty(reg) && reg != "0")
                        {
                            int reg1 = int.Parse(reg);
                            var area = dc.Areas.FirstOrDefault(p => p.AreaID == reg1);
                            if (area != null)
                            {
                                area.Countries.Load();
                                foreach (var coun in area.Countries)
                                {
                                    foreach (var role in roles)
                                    {
                                        if (role.Name == coun.CountryID.ToString() && user.Roles.Where(p => p.RoleID == role.RoleID).Count() < 1)
                                        {
                                            user.Roles.Add(role);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
                dc.SaveChanges();
                return true;
            }
        }


        /// <summary>
        /// 获取CIO用户权限
        /// </summary>
        /// <param name="cil"></param>
        /// <returns></returns>
        public static string GetUserRoleOver(string cil)
        {
            using (var dc = new CCEntities())
            {
                var user = dc.Employees.FirstOrDefault(p => p.NameEN == cil);
                user.Roles.Load();
                string result = "";
                if (user.Roles.Where(p => p.Disabled == false && p.Name == "CIO Admin").Count() > 0)
                {
                    result = "Admin,";
                    return result;
                }
                if (user.Roles.Where(p => p.Disabled == false && p.Name == "CIO User").Count() > 0)
                {
                    foreach (var role in user.Roles.Where(p => p.Description == "+country+" && p.Disabled == false).ToArray())
                    {
                        int countryid = int.Parse(role.Name);
                        var country1 = dc.Countries.FirstOrDefault(p => p.CountryID == countryid);
                        result += "Country;" + role.Name + ";" + country1.Name + "(" + country1.Description + "),";
                    }
                }
                return result;
            }
        }

        public static string[] CheckURL(string[] qstring, string cil)
        {
            using (var dc = new CCEntities())
            {
                var user = dc.Employees.FirstOrDefault(p => p.NameEN == cil);
                if (user == null)
                    return null;
                user.Roles.Load();
                if (user.Roles.Where(p => p.IsAdmin == true && p.Disabled == false && p.BelongsTo == "Admin").Count() > 0)
                    return qstring;
                var role1s = user.Roles.Where(p => p.IsAdmin == true && p.Disabled == false).ToArray();
                foreach (var str in qstring)
                {
                    if (dc.SP_GetRolesByEmployeeName(cil).ToList<Role>().Where(p => p.BelongsTo == str).Count() ==0 &&
                        user.Roles.Where(p => p.IsAdmin == true && p.Disabled == false && p.BelongsTo == str).Count() == 0)
                    {
                        throw new System.Security.Authentication.AuthenticationException("Access Denied");
                    }
                }
                return qstring;
            }
        }


        /// <summary>
        /// 定义用户属于那种角色
        /// </summary>
        /// <param name="employeeNo"></param>
        /// <param name="type"></param>
        private void DefineRole(string employeeNo, string type)
        {
            using (var dc = new CCEntities())
            {
                var employee = dc.Employees.First(p => p.EmployeeNo == employeeNo);
                if (employee != null)
                {
                    var role = dc.Roles.FirstOrDefault(p => p.Name == type);
                    if (role != null)
                        employee.Roles.Add(role);
                }
                dc.SaveChanges();
            }
        }

    }

    /// <summary>
    /// 获取用户已有权限
    /// </summary>
    public class CIORoleShowModel
    {
        public string RoleType { get; set; }
        public string CommercialType { get; set; }
        public string RoleValue { get; set; }
    }
}
